<?php

namespace app\api\controller;

use app\api\model\AttachmentModel;
use app\api\model\SystemModel;
use app\common\server\WeChatServer;
use OSS\OssClient as AliOssClient;
use OSS\Core\OssException;
use think\response\Json;

/**
 *
 */
class Uploadify extends ApiBase
{
    protected $alioss_accessKeyId;
    protected $alioss_accessKeySecret;
    protected $alioss_endpoint;
    protected $alioss_bucket;

    protected $path_name = [
        "SP" => 'uploads/goods/', // 商品相关
        "TX" => 'uploads/avatar/', // 头像相关
        "SH" => 'uploads/audit/', // 审核相关
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 阿里云图片上传
     * @throws OssException
     */
    public function uploadImage()
    {
        $file = $this->request->file('multipartFileList');
        $param = $this->request->post();


        if (empty($file) || $file->getError()) {
            $this->_error("错误");
        }

        $path_type = isset($param['path_name']) ? $this->path_name[$param['path_name']] : 'uploads/images/';

        $path_name = "images/" . $path_type  . date("Ymd") . "/";

        $image_upload_limit_size = config('ueditor.imageMaxSize'); // 图片大小
        $image_allow_files = config('ueditor.imageAllowFiles'); // 图片类型

        $file_info = $file->getInfo();
        // 大小验证
        if ($file_info['size'] > $image_upload_limit_size) {
            $this->_error("文件过大");
        }

        // 类型验证
        $extension = substr(strrchr($file_info['name'], '.'), 0);
        if (!in_array($extension, $image_allow_files)) {
            $this->_error("图片类型不正确");
        }

        //得到今天日期
        $today = date('YmdHis', time());
        $file_name = md5($today . $file_info['name']) . $extension;
        $result = $this->ossUpload($file_info, $file_name, $path_name);

        if (!empty($result['err_code'])) {
            return json($result);
        }
        $alioss_full_name = $result['info']['url'];
        $sub = substr($alioss_full_name, strripos($alioss_full_name, "com") + 3);   // 将阿里下载地址替换为自己的域名
        $alioss_full_name = config("ueditor.ossUrl") . $sub;


        $data = [
            "title" => $file_info['name'],  // 原名
            "original" => $file_name, // 上传后名字
            "path_type" => $path_type,
            "size" => $file_info['size'],
            "ext" => $extension,
            "type" => "image",
            "url" => $alioss_full_name,
            "hash" => $result['x-oss-hash-crc64ecma'],
            "uid" => $this->user_id,
            "date" => $today
        ];

        $this->_success("成功", $data);
    }

    /**
     * 阿里云视频上传
     * @return array
     * @throws OssException
     */
    public function uploadVideo()
    {
        $file = $this->request->file('file');
        $param = $this->request->post();
        if (empty($file) || $file->getError()) {
            return [
                'err_code' => ERRNO['UPLOADERR'],
                'msg' => ERRNO_MAP['UPLOADERR']
            ];
        }

        if (empty($param) || empty($param['path_name'])) {
            return [
                'err_code' => ERRNO['PARAMERR'],
                'msg' => ERRNO_MAP['PARAMERR']
            ];
        }
        $path_type = $param['path_name'];
        $path_name = "video/" . $path_type . "/" . date("Ymd") . "/";

        $video_upload_limit_size = config('ueditor.videoMaxSize'); // 视频大小
        $video_allow_files = config('ueditor.videoAllowFiles'); // 视频类型

        $file_info = $file->getInfo();
        // 大小验证
        if ($file_info['size'] > $video_upload_limit_size) {
            return [
                'err_code' => ERRNO['UPLOADSIZEERR'],
                'msg' => ERRNO_MAP['UPLOADSIZEERR']
            ];
        }

        // 类型验证
        $extension = substr(strrchr($file_info['name'], '.'), 0);
        if (!in_array($extension, $video_allow_files)) {
            return [
                'err_code' => ERRNO['UPLOADTYPEERR'],
                'msg' => ERRNO_MAP['UPLOADTYPEERR']
            ];
        }

        //得到今天日期
        $today = date('YmdHis', time());
        $file_name = md5($today . $file_info['name']) . $extension;
        $result = $this->ossUpload($file_info, $file_name, $path_name);
        $alioss_full_name = $result['info']['url'];

        $data = [
            "title" => $file_info['name'],
            "original" => $file_name,
            "path_type" => $path_type,
            "size" => $file_info['size'],
            "ext" => $extension,
            "type" => "video",
            "url" => $alioss_full_name,
            "hash" => $result['x-oss-hash-crc64ecma'],
            "uid" => $this->uid,
        ];

        return json(AttachmentModel::attachmentSave($data));
    }

    /**
     * 阿里云图片上传
     * @throws OssException
     */
    public function uploadFile()
    {
        $this->IsPower();
        $file = $this->request->file('file');
        $param = $this->data_post;
        if (empty($file) || $file->getError()) {
            return json(
                [
                    'err_code' => ERRNO['UPLOADERR'],
                    'msg' => ERRNO_MAP['UPLOADERR']
                ]
            );
        }
        if (empty($param) || empty($param['path_name'])) {
            return json(
                [
                    'err_code' => ERRNO['PARAMERR'],
                    'msg' => ERRNO_MAP['PARAMERR']
                ]
            );
        }
        $path_type = $param['path_name'];
        $path_name = "images/" . $path_type . "/" . date("Ymd") . "/";
        $image_upload_limit_size = config('ueditor.imageMaxSize'); // 图片大小
        $image_allow_files = config('ueditor.imageAllowFiles'); // 图片类型

        $file_info = $file->getInfo();
        // 大小验证
        if ($file_info['size'] > $image_upload_limit_size) {
            return json([
                'err_code' => ERRNO['UPLOADSIZEERR'],
                'msg' => ERRNO_MAP['UPLOADSIZEERR']
            ]);
        }

        // 类型验证
        $extension = substr(strrchr($file_info['name'], '.'), 0);
        if (!in_array($extension, $image_allow_files)) {
            return
                json([
                    'err_code' => ERRNO['UPLOADTYPEERR'],
                    'msg' => ERRNO_MAP['UPLOADTYPEERR']
                ]);
        }

        //得到今天日期
        $today = date('YmdHis', time());
        $file_name = md5($today . $file_info['name']) . $extension;
        $result = $this->ossUpload($file_info, $file_name, $path_name);

        if (!empty($result['err_code'])) {
            return json($result);
        }
        $alioss_full_name = $result['info']['url'];
        $data = [
            "title" => $file_info['name'],  // 原名
            "original" => $file_name, // 上传后名字
            "path_type" => $path_type,
            "size" => $file_info['size'],
            "ext" => $extension,
            "type" => "image",
            "url" => $alioss_full_name,
            "hash" => $result['x-oss-hash-crc64ecma'],
            "uid" => $this->uid,
        ];

        return json(AttachmentModel::attachmentSave($data));
    }


    /**
     * 阿里云上传
     * @param $file
     * @param $extension
     * @param $file_name
     * @param $path_name
     * @return array|null
     * @throws OssException
     */
    public function ossUpload($file, $file_name, $path_name)
    {
        //oss 配置项
        $ossconfig_data = WeChatServer::getOssConfig();

        if (empty($ossconfig_data) || empty($ossconfig_data['alicloud_access_key']) || empty($ossconfig_data['alicloud_access_key_secret']) || empty($ossconfig_data['alicloud_endpoint']) || empty($ossconfig_data['alicloud_bucket'])) {
            return [
                'err_code' => ERRNO['PARAMERR'],
                'msg' => ERRNO_MAP['PARAMERR']
            ];
        }

        $this->alioss_accessKeyId = $ossconfig_data['alicloud_access_key'];
        $this->alioss_accessKeySecret = $ossconfig_data['alicloud_access_key_secret'];
        $this->alioss_endpoint = $ossconfig_data['alicloud_endpoint'];
        $this->alioss_bucket = isset($ossconfig_data['alicloud_bucket']) ? trim($ossconfig_data['alicloud_bucket']) : '';

        //得到文件名
        $file_name = $path_name . $file_name;

        //实例化OSS
        $ossClient = new AliOssClient($this->alioss_accessKeyId, $this->alioss_accessKeySecret, $this->alioss_endpoint);
        try {
            //执行阿里云上传
            $result = $ossClient->uploadFile($this->alioss_bucket, $file_name, $file["tmp_name"]);
            return $result;
        } catch (OssException $e) {
            return [
                'err_code' => ERRNO['REQERR'],
                'msg' => $e->getMessage(),
            ];
        }
    }


}


?>